package ai.yale.service;

import ai.yale.bean.User;
import ai.yale.dao.UserRepository;
import ai.yale.util.CheckUtils;
import ai.yale.util.RespMessage;
import ai.yale.vo.LoginVo;
import ai.yale.vo.RegisterVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.UUID;

/**
 * Created by asus on 2017/8/17.
 */
@Service
public class UserService {

    @Autowired
    UserRepository userRepository;

    public RespMessage login(LoginVo vo) {

        if (CheckUtils.hasEmptyFields(vo)) {
            return RespMessage.fail(400, "缺少必填字段");
        }
        List<User> result = userRepository.findByUsername(vo.getUsername());
        if (result.size() != 1) {
            return RespMessage.fail(400, "用户名或密码不正确");
        }
        if (!vo.getPassword().equals(result.get(0).getPassword())) {
            return RespMessage.fail(400, "用户名或密码不正确");
        }
        return RespMessage.success(result.get(0));
    }

    public RespMessage reg(RegisterVo vo) {
        if (CheckUtils.hasEmptyFields(vo)) {
            return RespMessage.fail(400, "缺少必填字段");
        }
        List<User> existUser = userRepository.findByUsername(vo.getUsername());
        if (existUser.size() != 0) {
            return RespMessage.fail(400, "用户名已存在");
        }

        User user = new User();
        BeanUtils.copyProperties(vo, user);
        user.setId(UUID.randomUUID().toString());

        userRepository.save(user);
        return RespMessage.success(user);
    }

    public RespMessage list() {
        return RespMessage.success(userRepository.findAll());
    }
}
